let soc={};
/* importScripts("./pako.min.js");

//解压缩
async function unzip(data){
	let datas = await (new Response(data)).arrayBuffer(),str=[],len=data.length;	
	datas = pako.inflate(new Uint8Array(data));//unzip
	for(let i=0;i<len;i++){
		str[i]=String.fromCharCode(datas[i]);
	}	
	return str;
} */

//订阅
function subscribe(msg,resMsg){
	soc[msg.socketName].send(msg.content);
	resMsg.data=true;
	postMessage(resMsg);
}
//取消订阅
function unsubscribe(msg,resMsg){
	soc[msg.socketName].send(msg.content);
	resMsg.data=true;
	postMessage(resMsg);
}
//关闭
function close(msg,resMsg){
	if(soc[msg.socketName]){
		soc[msg.socketName].initiative=true;
		soc[msg.socketName].close();
	}		
	delete soc[msg.socketName];
	resMsg.data=true;
	postMessage(resMsg);
}
//连接
async function open(msg,resMsg){
	//创建websocket
	if(!msg.socketName || !msg.ws){
		console.log(`【${msg.socketName}】因参数无完整，无法建立连接`);
		postMessage(resMsg);
		return;
	}
	if(soc[msg.socketName]){
		console.log(`标识为【${msg.socketName}】websocket对象已经存在，无法建立连接`);
		postMessage(resMsg);
		return;
	}
	soc[msg.socketName]=await createWebsocket(msg.socketName,msg.ws,msg.zip);
	resMsg.data=soc[msg.socketName]?true:false;
	postMessage(resMsg);
}

//查询状态
function connectState(msg,resMsg){
	resMsg.data=soc[msg.socketName].isconnect
	postMessage(msg);
}

onmessage=ev=>{
	let msg=ev.data;
	let resMsg={
		id:msg.id,
		socketName:msg.socketName,
		data:null,
		type:msg.type
	}	
	if(msg.type=="open" || (soc[msg.socketName] && self[msg.type])){
		self[msg.type](msg,resMsg);
	}else{
		postMessage(resMsg);
	}
	ev=null;
}

/**
 * @description 在worker中建立websocket,连接对象缓存到soc对象中
 * @param {String} socketName 缓存名,用于标识websocket对象
 * @param {String} ws websocket连接地址
 * @param {String} zip 数据是否需要zip解压
 */

function createWebsocket(socketName,ws){
	return new Promise(resolve=>{
		let socket=new WebSocket(ws);
		console.log(`【${socketName}】正在连接...`);
		socket.onopen=ev=>{
			socket.isconnect=true;
			resolve(socket);
			console.log(`【${socketName}】连接成功`);
		}
		socket.onmessage=ev=>{
			let data=ev.data;
			postMessage({socketName,data,type:'soc'});
			data=null;
		}
		socket.onerror=ev=>{
			console.log(`【${socketName}】连接错误`,ev);
			resolve(null);
		}
		socket.onclose=ev=>{
			//非主动关闭自动重连
			socket.isconnect=false;
			if(!socket.initiative){
				console.log(`【${socketName}】连接关闭,5s后重新连接`,ev);
				setTimeout(async()=>{
					soc[socketName]=await createWebsocket(socketName,ws);
				},5000);
			}else{
				console.log(`【${socketName}】连接关闭`);
			}
			resolve(null);
		}
	})
	
}
